﻿
Namespace PL.CoreSDK
    Public Class SOP_PL
        Inherits PLBase
        Implements IPLProcess


        Public Property SequenceGeneration As Short = 2

        Public Sub New()
            MyBase.New()
        End Sub

        Public Sub New(ByVal queryName As String)
            MyBase.New(queryName)
        End Sub

        Public Overrides Function Delete() As Boolean
            'Throw New NotImplementedException("Delete To Come...")
            Return False
        End Function

        Public Overrides Function Validate() As Boolean
            'Throw New NotImplementedException("Validate To Come...")
            Return True
        End Function

        Public Overrides Sub ValidateRow(row As DataRow)
            row.ClearErrors()

            'If row.Table.Columns.Contains("TypeId_FK") Then
            '    If IsDBNull(row("TypeId_FK")) Then
            '        row.SetColumnError("TypeId_FK", "Mandatory")
            '    End If
            'End If
            '

            '
            If row.HasErrors Then
                row.RowError = "Please check your columns, a validation error occur"
            End If
        End Sub

        Public Overridable Sub OnRowUpdating(ByVal sender As Object, ByVal e As SqlRowUpdatingEventArgs) Handles MetaDataTable.OnRowUpdating
            If e.Command.CommandText = "bsp_SOP_PL_Save" Then
                SequenceGeneration = AppOption.SOPGenerationSequenceCode

                'Pour le Save sur un ADD on assign la sequence
                Me.MetaDataTable.Adapter.InsertCommand.Parameters("@GenerateSEQ").Value = SequenceGeneration
                Me.MetaDataTable.Adapter.UpdateCommand.Parameters("@GenerateSEQ").Value = SequenceGeneration

            End If
        End Sub

        Public Shared Function ExportDocTemplate(ByVal filename As String, ByVal SOPID As Guid) As Boolean
            Using ms As SOP_PL = New SOP_PL("SOP")
                Try
                    ms.MetaDataTable.GetMetaCommand()
                    ms.MetaDataTable.MetaCommand.SQLWhere = String.Format("SOPId = '{0}'", SOPID)
                    ms.InitDataForExport()
                    ms.Dataset.DataSetName = SOPID.ToString
                    ms.Dataset.WriteXml(filename, XmlWriteMode.WriteSchema)
                    Return True
                Catch ex As Exception
                    Throw ex
                End Try
                Return False
            End Using
        End Function

        Public Shared Function ExportDocTemplateToMaster(ByVal SOPID As Guid) As Boolean
            Dim IsSaved As Boolean
            Using mcSource As SOP_PL = New SOP_PL("SOP")
                Try
                    mcSource.MetaDataTable.GetMetaCommand()
                    mcSource.MetaDataTable.MetaCommand.SQLWhere = String.Format("SOPId = '{0}'", SOPID)
                    mcSource.InitDataForExport()
                    mcSource.Dataset.DataSetName = SOPID.ToString
                    For Each oTable As DataTable In mcSource.Dataset.Tables
                        For Each oRow As DataRow In oTable.Rows
                            oRow.SetAdded()
                        Next
                    Next

                    'Bypass pour ne plus utiliser la connection par défaut
                    AppManager.IsConnected = False
                    AppManager.OverrideByPassConnectionStringTOMaster = True

                    'Indique qu'elle connection utiliser dans le App.Config
                    AppManager.ConnectionConfigName = "ConnectionToMyMaster"
                    Using mcDest As SOP_PL = New SOP_PL("SOP")
                        mcDest.InitData()
                        mcDest.Dataset.Merge(mcSource.Dataset)
                        IsSaved = mcDest.Save()
                    End Using
                    Return IsSaved
                Catch ex As Exception
                    Throw ex
                Finally

                    'Remet en route la connection par défaut
                    AppManager.IsConnected = True
                    AppManager.OverrideByPassConnectionStringTOMaster = False

                    'Change pour utiliser la connection par défaut
                    AppManager.ConnectionConfigName = Nothing
                End Try
                Return False
            End Using
        End Function

        Public Shared Function ImportSOP(ByVal fileName As String) As Boolean
            Using dset As DataSet = New DataSet()
                dset.ReadXml(fileName, XmlReadMode.ReadSchema)
                Using ms As SOP_PL = New SOP_PL("SOP")
                    'Hack: DataSet must be fill to have adaptercommand and merge...
                    ms.InitData()
                    ms.Dataset.Merge(dset)
                    Return ms.Save()
                End Using
            End Using
        End Function

        Public Function InitDataForExport() As Boolean
            Dim metaDataTableChild As CommonExt.MetaDataTable
            Dim aChildRelationField As String
            Dim parentGuid As Guid = Guid.Empty
            Try
                Me.MetaDataTable.FillBusinessApplicationData()
                Me.Dataset.Tables.Add(Me.MetaDataTable)
                'ici on veux un record seulement
                If Not String.IsNullOrEmpty(Me.MetaDataTable.MetaCommand.SQLWhere) Then
                    parentGuid = CType(Me.MetaDataTable.Rows(0).Item(0), Guid)
                End If
                Dim aParentRelationField As String = Me.MetaDataTable.MetaCommand.GUIDField
                For Each row As DataRow In Me.MetaDataTable.MetaCommand.GetChildDisplayQuery.Rows
                    metaDataTableChild = New CommonExt.MetaDataTable() With {.QueryName = row("QueryName").ToString}
                    aChildRelationField = Me.MetaDataTable.MetaCommand.GUIDField & "_FK"
                    '
                    metaDataTableChild.GetMetaCommand()
                    '
                    If parentGuid <> Guid.Empty Then
                        metaDataTableChild.MetaCommand.SQLWhere = String.Format("{0} = '{1}'", aChildRelationField, parentGuid)
                    End If
                    '
                    metaDataTableChild.FillBusinessApplicationData()
                    '
                    Me.Dataset.Tables.Add(metaDataTableChild)
                    Dim aDR As New DataRelation(row("Relation").ToString, Me.MetaDataTable.Columns(aParentRelationField), metaDataTableChild.Columns(aChildRelationField))
                    Me.Dataset.Relations.Add(aDR)
                Next
                Return True
            Catch ex As Exception
                Throw ex
            End Try
            Return False
        End Function

        Public Function BatchRecords(dataRow() As DataRow) As Boolean Implements IPLProcess.BatchRecords
            Return True
        End Function

        Public Function CurrentRecord(dataRow As DataRow) As Boolean Implements IPLProcess.CurrentRecord
            Return True
        End Function

        Public Function NewRecord(dataRow As DataRow) As Boolean Implements IPLProcess.NewRecord
            'Si on arrive d'un TreeList...
            If Me.ID IsNot Nothing Then
                dataRow("SOPID") = ID
            Else
                dataRow("SOPID") = Guid.NewGuid
            End If

            Return True
        End Function
    End Class
	End Namespace
